package com.wuyangnju.lj.simulation.master.service;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wuyangnju.lj.simulation.common.Plan;
import com.wuyangnju.lj.simulation.master.model.ComputionData;
import com.wuyangnju.lj.simulation.master.model.snapshot.ComputionDataSnapshot;

public class ComputionThread extends Thread {
	private static final Log log = LogFactory.getLog(ComputionThread.class);

	public static final int INIT_SLEEP_MILISECONDS = 300 * 1000;
	public static final int SCREENING_GAP = 120 * 60 * 1000;
	public static final int INIT_PLAN_DATA_COUNT = 10;
	public static final int PROCESS_SLEEP_MILISECONDS = 60 * 1000;

	private boolean discarded = false;
	private ComputionData computionData;
	private double alpha, theta, k;

	public ComputionThread(ComputionData computionData, double alpha,
			double theta, double k) {
		this.computionData = computionData;
		this.alpha = alpha;
		this.theta = theta;
		this.k = k;
	}

	public void discard() {
		discarded = true;
	}

	public void run() {
		try {
			log.info("compution main loop started");
			// while (!computionData.snapshot().ready(INIT_PLAN_DATA_COUNT)) {
			// if (discarded)
			// return;
			// Thread.sleep(INIT_SLEEP_MILISECONDS);
			// if (discarded)
			// return;
			// log.info("waiting ready loop");
			// }

			Thread.sleep(SCREENING_GAP);
			log.info("compution ready");

			ComputionDataSnapshot computionDataSnapshot;
			List<Plan> planToRemove;

			// screening
			computionDataSnapshot = computionData.snapshot();
			planToRemove = computionDataSnapshot.processForScreening(0.02,
					k);
			computionData.removePlan(planToRemove);
			computionData.fixVar();

			while (!computionDataSnapshot.complete()) {
				Thread.sleep(PROCESS_SLEEP_MILISECONDS);
				computionDataSnapshot = computionData.snapshot();
				planToRemove = computionDataSnapshot.process2(0.03, theta,
						k);
				computionData.removePlan(planToRemove);
				if (discarded)
					return;
				log.info("process loop");
			}
			log.info("compution complete successfully. choose "
					+ computionData.snapshot().currentPlans().get(0));

		} catch (InterruptedException e) {
			log.error("compution init or start has been interrupted.", e);
		}
	}
}